let node_require_directory = require('node-require-directory');
let stringUtils = require('../utils/stringUtils');

// load routers recursively.
function recurseRouters(router, routers, urlPath, is_recursive) {

    urlPath = urlPath || '';
    if (!stringUtils.endWith(urlPath, '/')) {
        urlPath += '/';
    }
    if (!stringUtils.startWith(urlPath, '/')) {
        urlPath = '/' + urlPath;
    }
    Object.keys(routers).forEach(function (key) {
        if (key === 'index') return;
        if (typeof(routers[key]) === 'object') {
            // if key is endWith '&', the key has the same as a router function. delete the '&'
            let originalKey = null;
            // only end with & is sub router, $ is not a sub router
            if (key.charAt(key.length - 1) == '&') {
                // end with &, sub router
                originalKey = key.substr(0, key.length - 1);
            } else if (key.charAt(key.length - 1) == '$') {
                // end with $, not a sub router
                // originalKey = key;
                return;
            } else {
                originalKey = key;
            }
            if (is_recursive) {
                recurseRouters(router, routers[key], urlPath + originalKey + '/', is_recursive);
            }

        } else if (typeof(routers[key]) === 'function') {
            let newKey = key;
            if (key == 'homepage') {
                // home page path
                newKey = '';
            }
            router.use(urlPath + newKey, routers[key]);
        }
    });
}

module.exports = function (router, urlPath, filePath) {
    let routers;
    if (filePath) {
        routers = node_require_directory(__dirname + filePath);
    } else {
        routers = node_require_directory(__dirname);
    }

    recurseRouters(router, routers, urlPath, true);
};